#include "stm32f10x.h"                  // Device header

/**
  * @brief		初始化PWM功能
  * @parm		无
  * @retval		无
  */
void PWM_Init(void)
{
	//开启时钟
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);	
	
	//初始化GPIO
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;				//注意使用复用推挽输出
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	//内部时钟
	TIM_InternalClockConfig(TIM2);
	
	//时基单元
	TIM_TimeBaseInitTypeDef TIM_InitStructure;
	TIM_InitStructure.TIM_ClockDivision = TIM_CKD_DIV1;			//时钟分频
	TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up;		//向上计数
	TIM_InitStructure.TIM_Period = 100 - 1;						//重装值，计数周期
	TIM_InitStructure.TIM_Prescaler = 720 - 1;						//预分频
	TIM_InitStructure.TIM_RepetitionCounter = 0;				//重复计数，高级定时器才有
	TIM_TimeBaseInit(TIM2, &TIM_InitStructure);
	
	//输入/比较器模块
	TIM_OCInitTypeDef TIM_OCInitStructure;
	TIM_OCStructInit(&TIM_OCInitStructure);		//因为一些属性是高级定时器的，初始化给个初始值
	//配置
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;				//输出比较模式
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;		//极性，此处设置为高电平
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;	//使能
	TIM_OCInitStructure.TIM_Pulse = 0;								//比较值，即CCR
	TIM_OC1Init(TIM2, &TIM_OCInitStructure);
	
	//开启时钟
	TIM_Cmd(TIM2, ENABLE);
}

/**
  * @brief		设置比较值
  * @parm		Compare：比较值  范围：0 ~ 255
  * @retval		无
  */
void PWM_SetCompare(uint16_t Compare)
{
	TIM_SetCompare1(TIM2, Compare);
}

/**
  * @brief		设置分频值
  * @parm		Prescaler：分频值   范围：32位无符号
  * @retval		无
  */
void PWM_SetPrescaler(uint32_t Prescaler)
{
	//第三个参数选择立即更新还是使用影子寄存器，下次更新事件时才生效
	TIM_PrescalerConfig(TIM2, Prescaler, TIM_PSCReloadMode_Immediate);
}
